package com.fangcun.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

public class XStreamUtils {

	private static Logger LOG = LoggerFactory.getLogger(XStreamUtils.class);

	public static String beanToXml(Object obj) {
		XStream xStream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("_-", "_")));
		xStream.autodetectAnnotations(true);
		xStream.ignoreUnknownElements();
		xStream.setMode(XStream.NO_REFERENCES);
		return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xStream.toXML(obj);
	}

	@SuppressWarnings("unchecked")
	public static <T> T xmlToBean(Class<T> clazz, String xml) {
		try {
			XStream xStream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("_-", "_")));
			XStream.setupDefaultSecurity(xStream);
			xStream.allowTypes(new Class[] { clazz });
			xStream.allowTypesByWildcard(new String[] { "com.fangcun.**" });
			xStream.autodetectAnnotations(true);
			xStream.ignoreUnknownElements();
			xStream.processAnnotations(clazz);
			xStream.setClassLoader(clazz.getClassLoader());
			return (T) xStream.fromXML(xml);
		} catch (Exception e) {
			LOG.error("xml:{}xml解析异常：{}", xml, e.getMessage());
			throw new RuntimeException("[XStream]XML转对象出错");
		}
	}
}
